package com.hanhai.zrb.backend.web.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.hanhai.common.annotation.PermissionNeed;
import com.hanhai.common.web.controller.BaseController;
import com.hanhai.zrb.api.biz.dao.mybatis.UserDao;
import com.hanhai.zrb.api.biz.service.FundService;
import com.hanhai.zrb.api.biz.service.IndustryService;
import com.hanhai.zrb.api.biz.service.ProjectService;
import com.hanhai.zrb.api.biz.service.ResourceMatchService;
import com.hanhai.zrb.api.biz.service.SysDictionaryService;
import com.hanhai.zrb.backend.admin.model.BackendUser;
import com.hanhai.zrb.backend.util.BackendLoginUtil;
import com.hanhai.zrb.model.fund.vo.FundSearchVo;
import com.hanhai.zrb.model.intention.enums.IntentionTypeEnum;
import com.hanhai.zrb.model.photo.Photo;
import com.hanhai.zrb.model.photo.PhotoVo;
import com.hanhai.zrb.model.project.ProjectDetail;
import com.hanhai.zrb.model.resourcematch.ResourceMatchContent;
import com.hanhai.zrb.model.resourcematch.ResourceMatchLevelEnum;
import com.hanhai.zrb.model.resourcematch.ResourceMatchResult;
import com.hanhai.zrb.model.resourcematch.ResourceMatchTypeEnum;
import com.hanhai.zrb.model.user.User;

@Controller
@RequestMapping("/project")
public class ProjectController extends BaseController {

	@Autowired
	private ProjectService projectService;

	@Autowired
	private SysDictionaryService sysDictionaryService;

	@Autowired
	private IndustryService industryService;

	@Autowired
	private UserDao userDao;
	
	@Autowired
	private ResourceMatchService resourceMatchService;
	
	@Autowired
	private FundService fundService;

	@RequestMapping("/index")
	public String index() {
		return "project/list";
	}

	@RequestMapping("/my")
	public String my(Model model) {
		Integer my = 1;
		model.addAttribute("my", my);
		return "project/list";
	}
	
	@RequestMapping("/auditindex")
	public String auditindex() {
		return "project/auditlist";
	}

	@RequestMapping("/selIntention")
	public String selIntention() {
		return "project/selIntention";
	}

	@PermissionNeed("project")
	@RequestMapping("list")
	public void list(ProjectDetail projectDetail, Integer page,Integer rows,Integer my,
			HttpServletResponse response) throws IOException {
		if(page==null){
			page=1;
		}
		if(rows==null){
			rows=20;
		}
		BackendUser baseUser = BackendLoginUtil.getCurrentUser();
		if(my != null){
			projectDetail.setUserId(baseUser.getId());
		}
		handleSearchAll(projectDetail);
		Map<String, Object> map = new HashMap<String, Object>();
		// PageInfo pageInfo = projectService.listAll(projectDetail, page,
		// rows);
		PageInfo pageInfo = projectService.listAllFromSolr(projectDetail, page,
				rows);
		map.put("rows", pageInfo.getList());
		map.put("total", pageInfo.getTotal());
		String str = JSONObject.toJSONString(map);
		response.getWriter().write(str);
	}

	private void handleSearchAll(ProjectDetail projectDetail) {
		//行业搜索-1，表示“所有”，不限制条件
		if(projectDetail.getIndustryId() != null && projectDetail.getIndustryId().equals(-1)){
			projectDetail.setIndustryId(null);
		}
		if(projectDetail.getProvincePostcode()!=null && projectDetail.getProvincePostcode().endsWith("-1")){
			projectDetail.setProvincePostcode(null);
		}
		Short status = -1;
		if(projectDetail.getProjectStatus() != null && projectDetail.getProjectStatus().equals(status)){
			projectDetail.setProjectStatus(null);
		}
		if(projectDetail.getAuth() != null && projectDetail.getAuth().equals(-1)){
			projectDetail.setAuth(null);
		}
		if(projectDetail.getMode() != null && projectDetail.getMode().equals(-1)){
			projectDetail.setMode(null);
		}
	}

	@PermissionNeed("project")
	@RequestMapping("/selfund")
	public String selfund() {
		return "project/selfund";
	}

	@PermissionNeed("project")
	@RequestMapping("doadd")
	public void doadd(HttpServletRequest request, HttpServletResponse response) {

		ProjectDetail projectDetail = new ProjectDetail();

		// 从request获取

		/*
		 * if (projectService.isExsitedProjectNo(
		 * request.getParameter("projectNo"), 0L)) { super.jsonFail(response,
		 * "新增失败，该项目编号已存在，请重新输入！"); return; }
		 */
		projectDetail.setProjectNo(request.getParameter("projectNo"));
		projectDetail.setProjectName(request.getParameter("projectName"));
		// projectDetail.setPic(request.getParameter("pic"));
		projectDetail.setMode(Integer.parseInt(request.getParameter("mode")));
		projectDetail.setTotal(new BigDecimal(request.getParameter("total")));
		projectDetail.setIndustryId(Integer.parseInt(request
				.getParameter("industryId")));
		projectDetail.setProvincePostcode(request
				.getParameter("provincePostcode"));
		projectDetail.setProvince(request.getParameter("province"));
		String phone = request.getParameter("phone");
		if (null == phone) {
			super.jsonFail(response, "发布人手机不能为空");
			return;
		} else {
			User pushUser = userDao.findByPhone(phone);
			if (null == pushUser) {
				super.jsonFail(response, "发布人不存在，请重新检查发布人账号");
				return;
			} else {
				projectDetail.setPusher(String.valueOf(pushUser.getUid()));
				projectDetail.setPhone(phone);
			}
		}
		projectDetail.setAuth(Integer.parseInt(request.getParameter("auth")));
		if (null != request.getParameter("intentionId")
				&& !"".equals(request.getParameter("intentionId"))) {
			if (projectService.isBindIntention(
					Long.parseLong(request.getParameter("intentionId")), 0L)) {
				super.jsonFail(response, "新增失败，该意向已经绑定过项目，请重新选择！");
				return;
			}
			projectDetail.setIntentionId(Long.parseLong(request
					.getParameter("intentionId")));
		}
		projectDetail.setIntro(request.getParameter("intro"));
		projectDetail.setAddress(request.getParameter("address"));
		projectDetail.setGeocoor(request.getParameter("geocoor"));
		projectDetail.setDestionation(request.getParameter("destionation"));
		projectDetail.setProMode(request.getParameter("proMode"));
		projectDetail.setAdvantage(request.getParameter("advantage"));
		projectDetail.setPlan(request.getParameter("plan"));
		projectDetail.setCompany(request.getParameter("company"));
		projectDetail.setProduct(request.getParameter("product"));
		projectDetail.setTeam(request.getParameter("team"));
		projectDetail.setCompletion(request.getParameter("completion"));
		// 处理表单数据
		BackendUser backendUser = BackendLoginUtil.getCurrentUser();
		projectDetail.setUserId(backendUser.getId());
		projectDetail.setUserName(backendUser.getUserName());
		projectService.add(projectDetail);

		super.jsonSucceed(response);

	}

	@PermissionNeed("project")
	@RequestMapping("doupdate")
	public void doupdate(HttpServletRequest request,
			HttpServletResponse response, Integer mode, String total,
			Integer industryId, Integer auth) {
		ProjectDetail projectDetail = new ProjectDetail();
		// 从request获取
		projectDetail.setId(Long.parseLong(request.getParameter("id")));
		/*
		 * if (projectService.isExsitedProjectNo(
		 * request.getParameter("projectNo"), projectDetail.getId())) {
		 * super.jsonFail(response, "修改失败，该项目编号已存在，请重新输入！"); return; }
		 */
		projectDetail.setProjectNo(request.getParameter("projectNo"));
		projectDetail.setProjectName(request.getParameter("projectName"));
		// projectDetail.setPic(request.getParameter("pic"));
		projectDetail.setMode(mode);
		if (total != null) {
			projectDetail.setTotal(new BigDecimal(total));
		}
		projectDetail.setIndustryId(industryId);
		projectDetail.setProvincePostcode(request
				.getParameter("provincePostcode"));
		projectDetail.setProvince(request.getParameter("province"));
		String phone = request.getParameter("phone");
		if (null == phone) {
			super.jsonFail(response, "发布人手机不能为空");
			return;
		} else {
			User pushUser = userDao.findByPhone(phone);
			if (null == pushUser) {
				super.jsonFail(response, "发布人不存在，请重新检查发布人账号");
				return;
			} else {
				projectDetail.setPusher(String.valueOf(pushUser.getUid()));
				projectDetail.setPhone(phone);
			}
		}

		projectDetail.setAuth(auth);
		if (null != request.getParameter("intentionId")
				&& !"".equals(request.getParameter("intentionId"))) {
			if (projectService.isBindIntention(
					Long.parseLong(request.getParameter("intentionId")),
					projectDetail.getId())) {
				super.jsonFail(response, "修改失败，该意向已经绑定过项目，请重新选择！");
				return;
			}
			projectDetail.setIntentionId(Long.parseLong(request
					.getParameter("intentionId")));
		}
		projectDetail.setIntro(request.getParameter("intro"));
		projectDetail.setAddress(request.getParameter("address"));
		projectDetail.setGeocoor(request.getParameter("geocoor"));
		projectDetail.setDestionation(request.getParameter("destionation"));
		projectDetail.setProMode(request.getParameter("proMode"));
		projectDetail.setAdvantage(request.getParameter("advantage"));
		projectDetail.setPlan(request.getParameter("plan"));
		projectDetail.setCompany(request.getParameter("company"));
		projectDetail.setProduct(request.getParameter("product"));
		projectDetail.setTeam(request.getParameter("team"));
		projectDetail.setCompletion(request.getParameter("completion"));

		projectService.update(projectDetail);

		super.jsonSucceed(response);
	}

	@PermissionNeed("project")
	@RequestMapping("dodelete")
	public void dodelete(long id, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		projectService.delete(id);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("success", true);
		String str = JSONObject.toJSONString(map);
		response.getWriter().write(str);
	}

	@PermissionNeed("project")
	@RequestMapping("doaudit")
	public void doaudit(long id, short status, HttpServletResponse response) {

		projectService.audit(id, status);

		super.jsonSucceed(response);
	}

	@PermissionNeed("project")
	@RequestMapping("checkProjectNo")
	public void checkProjectNo(long curProjectId, String projectNo,
			HttpServletResponse response) {
		if (projectService.isExsitedProjectNo(projectNo, curProjectId)) {
			super.jsonFail(response, "该项目编号已存在，请重新输入！");
			return;
		}

		super.jsonSucceed(response);
	}

	@PermissionNeed("project")
	@RequestMapping("checkPhone")
	public void checkPhone(String phone, HttpServletResponse response) {
		User pushUser = userDao.findByPhone(phone);
		if (null == pushUser) {
			super.jsonFail(response, "发布人不存在，请重新检查发布人账号");
			return;
		}

		super.jsonSucceed(response);
	}

	@PermissionNeed("project")
	@RequestMapping("checkIntention")
	public void checkIntention(long intentionId, long projectId,
			HttpServletResponse response) {
		if (projectService.isBindIntention(intentionId, projectId)) {
			super.jsonFail(response, "该意向已经绑定过项目，请重新选择！");
			return;
		}

		super.jsonSucceed(response);
	}

	// 迁移项目主图
	@PermissionNeed("project")
	@RequestMapping("migratePic")
	public void migratePic(HttpServletResponse response) {
		boolean succeed = true;
		try {
			projectService.migratePic();
		} catch (Exception e) {
			succeed = false;
			e.printStackTrace();
			logger.error("migratePic failed", e);
		}
		if (succeed) {
			super.jsonSucceed(response);
		} else {
			super.jsonFail(response, "migratePic failed");
		}
	}

	@PermissionNeed("project")
	@RequestMapping("viewPhoto")
	public String viewPhoto(HttpServletResponse response, Model model,
			@RequestParam Long id) {
		PhotoVo photoVo = projectService.viewPhoto(id);
		/*
		 * JSONObject jsonObject = new JSONObject(); jsonObject.put("photoVo",
		 * photoVo); super.returnJsonObject(response, jsonObject);
		 */
		model.addAttribute("photoVo", photoVo);
		return "project/viewPhoto";
	}

	@PermissionNeed("project")
	@RequestMapping("managePhoto")
	public String managePhoto(HttpServletResponse response, Model model,
			@RequestParam Long id) {
		PhotoVo photoVo = projectService.viewPhoto(id);
		model.addAttribute("photoVo", photoVo);
		return "project/managePhoto";
	}

	// 如果没有1个图是主图，默认第1个为主图
	@PermissionNeed("project")
	@RequestMapping("savePhoto")
	public void savePhoto(HttpServletResponse response, @RequestParam Long id,
			String photos) {
		List<Photo> list = JSONArray.parseArray(photos, Photo.class);
		projectService.savePhoto(id, list,1);
		super.jsonSucceed(response);
	}

	// 上线订正项目
	@RequestMapping("updateProjectNo")
	public void updateProjectNo(HttpServletResponse response, Integer update) {
		boolean succeed = true;
		try {
			projectService.updateProjectNo(update);
		} catch (Exception e) {
			e.printStackTrace();
			succeed = false;
		}
		if (succeed) {
			super.jsonSucceed(response);
		} else {
			super.jsonFail(response, "updateProjectNo failed");
		}
	}

	// 上线订正资金
	@RequestMapping("updateFundNo")
	public void updateFundNo(HttpServletResponse response, Integer update) {
		boolean succeed = true;
		try {
			projectService.updateFundNo(update);
		} catch (Exception e) {
			e.printStackTrace();
			succeed = false;
		}
		if (succeed) {
			super.jsonSucceed(response);
		} else {
			super.jsonFail(response, "updateFundNo failed");
		}
	}
	
	
	@RequestMapping("/showMarryFund")
	public String showMarryFund(String id,Integer type,HttpServletRequest request,HttpServletResponse response) {
		Long ids = null;
		if( StringUtils.isNotBlank(id)){
			ids = Long.valueOf(id);
			List<FundSearchVo> findFundSearchVo = new ArrayList<FundSearchVo>();
			ResourceMatchResult recommends = new ResourceMatchResult();
			if( type!=null && type.equals(IntentionTypeEnum.project.getCode())){
				recommends = resourceMatchService.recommend(ResourceMatchTypeEnum.INTENTION_PROJECT.getCode(), ids );
			}else{
				recommends = resourceMatchService.recommend(ResourceMatchTypeEnum.PROJECT.getCode(), ids );
			}
			findFundSearchVo = getListVo(recommends);
			request.setAttribute("id", id);
			if( type == null){
				type = 103;
			}
			request.setAttribute("type", type);
			request.setAttribute("queryByIdsList", findFundSearchVo);
			}
		return "project/showMarryFund";
	}

	private List<FundSearchVo> getListVo(ResourceMatchResult recommends) {
		List<ResourceMatchContent> recommend = recommends.getResourceMatchContentList();
		List<Long> list = new ArrayList<Long>() ;
		for (int i = 0; i < recommend.size(); i++) {
			list.add(recommend.get(i).getBizid());
		}
		List<FundSearchVo> findFundSearchVo = fundService.findFundSearchVo(list);
		return findFundSearchVo;
	}
	
	@RequestMapping("/queryMarryFundList")
	@ResponseBody
	public String queryFundUser(Long id ,Integer page ,Integer rows ,Integer level ,Integer type) {
		Map<String, Object> map = Maps.newHashMap();
		ResourceMatchResult matchPage = new ResourceMatchResult();
		if( type!=null && type.equals(IntentionTypeEnum.project.getCode())){
			matchPage = getResourceMatchResult(ResourceMatchTypeEnum.INTENTION_PROJECT.getCode(),id, page, rows, level, matchPage);
		}else{
			matchPage = getResourceMatchResult(ResourceMatchTypeEnum.PROJECT.getCode(),id, page, rows, level, matchPage);
		}
		Page<ResourceMatchContent> resourceMatchContentPage = matchPage.getResourceMatchContentPage();
		List<Long> list = new ArrayList<Long>();
		List<FundSearchVo> findFundSearchVo = new ArrayList<FundSearchVo>();
		if( null!=resourceMatchContentPage && !resourceMatchContentPage.isEmpty()){
			for (ResourceMatchContent resourceMatchContent : resourceMatchContentPage) {
				list.add(resourceMatchContent.getBizid());
			}
			if(!list.isEmpty()){
				findFundSearchVo = fundService.findFundSearchVo(list);
			}
			
		}
		if(findFundSearchVo != null && !findFundSearchVo.isEmpty()){
	    	map.put("rows", findFundSearchVo);
	    	map.put("total", resourceMatchContentPage.getTotal());
	    }else{
	    	map.put("rows", Lists.newArrayList());
	    	map.put("total", 0);
	    }
		return JSON.toJSONString(map);
	}

	private ResourceMatchResult getResourceMatchResult(Integer code ,Long id, Integer page,
			Integer rows, Integer level, ResourceMatchResult matchPage) {
		if( null == level || ResourceMatchLevelEnum.ALL.getCode().equals(level) ){
			matchPage = resourceMatchService.matchPage(
					code, id, page, rows,
					ResourceMatchLevelEnum.ALL);
		}else if( ResourceMatchLevelEnum.FIRST.getCode().equals(level)  ){
			matchPage = resourceMatchService.matchPage(
					code, id, page, rows,
					ResourceMatchLevelEnum.FIRST);
		}else if( ResourceMatchLevelEnum.SECOND.getCode().equals(level) ){
			matchPage = resourceMatchService.matchPage(
					code, id, page, rows,
					ResourceMatchLevelEnum.SECOND);
		}else if( ResourceMatchLevelEnum.THIRD.getCode().equals(level) ){
			matchPage = resourceMatchService.matchPage(
					code, id, page, rows,
					ResourceMatchLevelEnum.THIRD);
		}
		return matchPage;
	}
	
	
}
